﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using Interfaces;
using Utilites;
using DAOBase;

namespace Repository
{
    public class HostedFileRepository : IRepository<HostedFile>
    {
        private SmartDictionary hfiles = new SmartDictionary(
    (id) => { return hf_dao.LoadHostedFile(id); }
    );

        private static IHostedFileDAO hf_dao;

        public HostedFileRepository()
        {
            var facade = new DAOFacade();
            if (hf_dao == null)
                hf_dao = facade.GetFactory().GetHostedFileDAO();
        }


        public SmartDictionary GetAllObjects()
        {
            return hfiles;
        }

        public void InsertObject(HostedFile obj)
        {
            hfiles[obj.ID] = obj;
            obj.State = EntityState.New;
        }

        public void DeleteObject(HostedFile obj)
        {
            hfiles[obj.ID].State = EntityState.Deleted;
        }

        public void Go()
        {
            foreach (var rec in hfiles)
            {
                switch(rec.State)
                {
                    case EntityState.New: hf_dao.AddHostedFile((HostedFile)rec);
                        break;
                    case EntityState.Modified: hf_dao.ModifyHostedFile((HostedFile)rec); break;
                    case EntityState.Deleted: hf_dao.RemoveHostedFile((HostedFile)rec); break;
                }
                rec.State = EntityState.Unchanged;
            }
        }

        public void Reload()
        {
            foreach (var rec in hfiles)
            {
                hfiles[rec.ID] = hf_dao.LoadHostedFile(rec.ID);
            }
        }

        public void OnTimerUpdateInvoked(object sender, EventArgs e)
        {
            Reload();
        }
    }
}
